package com.itheima.utils;

import com.itheima.pojo.Setmeal;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


public class RedisUtil {

    private static RedisTemplate<String, Object> redisTemplate;

    /**
     * 初始化 redisTemplate
     * @param _redisTemplate
     */
    public static void register(RedisTemplate<String, Object> _redisTemplate){
        redisTemplate = _redisTemplate;
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }

    public static void set(String key,Object value){
        redisTemplate.opsForValue().set(key,value);
    }

    public static void set(String key,Object value,long timeout, TimeUnit unit){
        redisTemplate.opsForValue().set(key,value,timeout,unit);
    }

    public static <T> T get(String key){
        return (T) redisTemplate.opsForValue().get(key);
    }

    public static void removeOfSet(String key, Object... values){
        redisTemplate.opsForSet().remove(key,values);
    }

    public static void addToSet(String key, Object... values){
        redisTemplate.opsForSet().add(key,values);
    }

    /**
     * String类型的 判断key是否存在：redisTemplate.hasKey(String key)
     * @param key
     */
    public static Boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }
    //.map(fileKeyObj->(String)fileKeyObj).collect(Collectors.toSet());
    //这个方法是唯一的 不同项目这个东西得看情况
    public static Set<String> members(String key){
        return redisTemplate.opsForSet().members(key).stream().map(objKey->(String)objKey).collect(Collectors.toSet());
    }
    public static void putToHash(String key, String name, Setmeal values) {
        redisTemplate.<String ,Setmeal>opsForHash().put(key, name, values);
    }

    public static List<Setmeal> findAllOfHash(String key) {
        return redisTemplate.<String,Setmeal>opsForHash().values(key);
    }

    public static Setmeal getFromHash(String key, String name) {
        return redisTemplate.<String ,Setmeal>opsForHash().get(key, name);
    }

    public static void delete(String key, String name) {
        redisTemplate.<String ,Setmeal>opsForHash().delete(key, name);
    }

}
